package com.imooc.o2o.service.impl;

import com.imooc.o2o.dao.ShopDao;
import com.imooc.o2o.dto.ShopExecution;
import com.imooc.o2o.entity.Shop;
import com.imooc.o2o.enums.ShopStateEnum;
import com.imooc.o2o.exceptions.ShopOperationException;
import com.imooc.o2o.service.ShopService;
import com.imooc.o2o.util.ImageUtil;
import com.imooc.o2o.util.PathUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.File;
import java.util.Date;

/**
 * Created by PopQing on 2018/5/11.
 */
@Service
public class ShopServiceImpl implements ShopService {
    @Autowired
    private ShopDao shopDao;

    public ShopDao getShopDao() {
        return shopDao;
    }

    public void setShopDao(ShopDao shopDao) {
        this.shopDao = shopDao;
    }

    @Override
    @Transactional
    public ShopExecution addShop(Shop shop, File shopImg) {
        if(shop==null){
            return new ShopExecution(ShopStateEnum.NULL_SHOP);
        }
        if(shop.getArea()==null){
            return new ShopExecution(ShopStateEnum.NULL_SHOPAREA);
        }
        if(shop.getShopCategory()==null){
            return new ShopExecution(ShopStateEnum.NULL_SHOPCATEGORY);
        }
        try{
            //在增加店铺之前需要初始化参数
            shop.setEnableStatus(0);
            shop.setCreateTime(new Date());
            shop.setLastEditTime(new Date());
            int effectedNum = shopDao.insertShop(shop);
            if(effectedNum<=0){
                throw new ShopOperationException("店铺操作失败");
            }else{
                if(shopImg!=null){
                    try {
                        addShopImg(shop, shopImg);//shopId创建图片目录
                    }catch (Exception e){
                        throw new ShopOperationException("更新图片失败");
                    }
                    effectedNum = shopDao.updateShop(shop);
                    if(effectedNum<=0){
                        throw new ShopOperationException("更新图片地址失败");
                    }
                }
            }
        }catch (Exception e){
            throw new ShopOperationException("addShop error:"+e.getMessage());
        }
        return new ShopExecution(ShopStateEnum.CHECK,shop);
    }

    private void addShopImg(Shop shop,File shopImg){
        //获取shop图片目录的相对值路径
        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:"+shop.getShopId());
        String dest = PathUtil.getShopIamgePath(shop.getShopId());
        System.out.println("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
        String shopImgAddr = ImageUtil.generateThumbnail(shopImg,dest);
        System.out.println("ccccccccccccccccccccccccccccc");
        shop.setShopImg(shopImgAddr);
    }
}
